/**
 * 主进程
 */
import { app, shell, BrowserWindow, ipcMain, Menu, Tray, screen } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { saveWindow } from './window'
import {
	IpcLoginOrRegister,
	IpcLoginSuccess,
	IpcCloseElectron,
	IpcWinBtn,
	IpcSetData,
	IpcGetData,
	IpcOpenNewWindow,
	IpcLogout
} from './ipc'

const loginWidth = 260
const loginHeight = 260
const registerHeight = 350
app.commandLine.appendSwitch('lang', 'zh-CN') // 简体中文

function createWindow(): void {
	// Create the browser window.
	const mainWindow = new BrowserWindow({
		icon,
		width: loginWidth,
		height: loginHeight,
		show: false, // 隐藏窗口，等渲染进程准备好后再显示
		autoHideMenuBar: true, // 隐藏菜单栏
		resizable: false, // 禁止缩放
		titleBarStyle: 'hidden', // 试图隐藏标题栏，但保留边框
		titleBarOverlay: false, // 不使用标题栏覆盖
		frame: true, // 启用窗口边框
		// ...(process.platform === 'linux' ? { icon } : {}), // 不同环境下的图标
		webPreferences: {
			preload: join(__dirname, '../preload/index.js'),
			sandbox: false
		}
	})
	saveWindow('main', mainWindow) // 保存主窗口
	/**
	 * 托盘: 创建托盘图标并设置右键菜单
	 * @param icon 托盘图标路径
	 * @returns {Tray} 托盘对象
	 */
	const tray = new Tray(icon)
	const contextMenu = Menu.buildFromTemplate([
		{
			label: '退出豆包',
			click: () => {
				app.quit()
			}
		}
	])
	tray.setToolTip('豆包') // 鼠标悬停时显示的提示文本
	tray.setContextMenu(contextMenu) // 设置右键菜单
	// 监听托盘图标点击事件
	tray.on('click', () => {
		mainWindow.show()
	})

	// 监听窗口最大化/还原事件
	mainWindow.on('maximize', () => {
		mainWindow.webContents.send('window-maximize-changed', { isMaximized: true })
	})
	// 监听窗口还原事件
	mainWindow.on('unmaximize', () => {
		mainWindow.webContents.send('window-maximize-changed', { isMaximized: false })
	})
	IpcSetData()
	IpcGetData()
	IpcOpenNewWindow()
	// ipcMain.on('getData', (e, data) => {
	// 	console.log('获取===', data)
	// 	// e.sender.send('IpcGetData', getData(key))
	// })

	// 监听登录注册
	IpcLoginOrRegister((isRegister) => {
		mainWindow.setResizable(true)
		mainWindow.setMaximizable(false) // 允许最大化
		mainWindow.setSize(loginWidth, isRegister ? registerHeight : loginHeight)
		mainWindow.setResizable(false)
	})
	// 监听登录成功到首页
	IpcLoginSuccess((_data) => {
		// console.log('data===', data)
		// setData('token', data.params?.token)
		// win?.setMinimumSize(260, 260) // 确保允许缩小
		mainWindow.setMaximumSize(1200, 800) // 临时锁定最大尺寸
		mainWindow.setResizable(true) // 允许调整大小
		mainWindow.setSize(1200, 800)
		mainWindow.center() // 居中
		mainWindow.setMaximizable(true) // 允许最大化
		mainWindow.setMinimumSize(800, 600) // 设置最小尺寸
	})
	// 关闭electron
	IpcCloseElectron(() => {
		app.quit()
	})
	// 监听 electron 窗口按钮事件(置顶、最小化、最大化、关闭等)
	IpcWinBtn((e, { action, data }) => {
		// console.log('action===', action, data)
		const webContents = e.sender
		const win = BrowserWindow.fromWebContents(webContents) // 获取当前窗口
		switch (action) {
			case 'top': // 置顶/取消置顶
				win?.setAlwaysOnTop(data.top)
				break
			case 'minimize': // 最小化
				win?.minimize()
				break
			case 'maximize': // 最大化/还原
				win?.isMaximized() ? win?.unmaximize() : win?.maximize()
				// 通知渲染进程当前窗口状态
				e?.sender.send('window-maximize-changed', { isMaximized: win?.isMaximized() })
				break
			case 'close': // 0关闭 1隐藏
				data.closeType === 0 ? win?.close() : win?.hide()
				break
			default:
				break
		}
	})

	// 监听退出登录
	IpcLogout((e) => {
		const win = BrowserWindow.fromWebContents(e.sender)
		win?.setMinimumSize(260, 260) // 确保允许缩小
		win?.setMaximumSize(260, 260) // 临时锁定最大尺寸
		win?.setSize(260, 260)
		win?.center()
		win?.setMaximizable(false)
		// console.log('loginWidth==', loginWidth, loginHeight)
		// // mainWindow.setResizable(true) // 允许调整大小
		// mainWindow.setSize(260, 260)
		// mainWindow.center() // 居中
		// mainWindow.setMaximizable(false) // 允许最大化
	})

	mainWindow.on('ready-to-show', () => {
		mainWindow.show()
		mainWindow.setTitle('豆包')
	})

	mainWindow.webContents.setWindowOpenHandler((details) => {
		shell.openExternal(details.url)
		return { action: 'deny' }
	})

	// HMR for renderer base on electron-vite cli.
	// Load the remote URL for development or the local html file for production.
	if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
		mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
	} else {
		mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
	}
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
	// Set app user model id for windows
	electronApp.setAppUserModelId('com.electron')

	// Default open or close DevTools by F12 in development
	// and ignore CommandOrControl + R in production.
	// see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
	app.on('browser-window-created', (_, window) => {
		optimizer.watchWindowShortcuts(window)
	})

	// IPC test
	ipcMain.on('ping', () => console.log('pong'))

	createWindow()

	app.on('activate', function () {
		// On macOS it's common to re-create a window in the app when the
		// dock icon is clicked and there are no other windows open.
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
	// TODO 获取屏幕信息
	// console.log('screen===', screen.getPrimaryDisplay())
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
